﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WCYCReader.SocketServer.Models;

namespace WCYCReader.SocketServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        int Port = 8888;// 5000;
        // 服务器端的 IP 地址
        string strIP = CommonHelper.GetIPAddress();

        //负责监听 客户端 的连接请求
        Socket socketWatch = null;

        // 执行 socketWatch 对象监听请求的线程
        Thread threadWatch = null;

        public MainWindow()
        {
            InitializeComponent();
            txtIP.Text += "本地 IP：" + strIP;
            txtPort.Text = Port.ToString ();
        }

     

        // 开启监听
        private void btnBeginListening_Click(object sender, RoutedEventArgs e)
        {
            if (socketWatch == null)
            {
                //实例化 套接字 （ip4寻址协议，流式传输，TCP协议）
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(strIP), Port);

                //将 监听套接字  绑定到 对应的IP和端口
                socketWatch.Bind(endpoint);

                //设置 监听队列 长度为10(同时能够处理 10个连接请求)
                socketWatch.Listen(10);
                threadWatch = new Thread(StartWatch);
                threadWatch.IsBackground = true;
                threadWatch.Start();
                ShowMsg("启动服务器成功......\r\n");
            }
            else
            {
                ShowMsg("服务器已经启动");
            }
        }

        // 循环侦听客户端的连接请求
        bool isWatch = true;

        // 负责与客户端通信的对象
        SocketClient socketClient;

        /// <summary>
        /// 被线程调用 监听连接端口
        /// </summary>
        void StartWatch()
        {
            while (isWatch)
            {
                try
                {
                    //监听 客户端 连接请求，但是，Accept会阻断当前线程
                    //监听到请求，立即创建负责与该客户端套接字通信的套接字
                    Socket socket = socketWatch.Accept();

                    if (socketClient != null)
                        socketClient.CloseConnection();

                    socketClient = new SocketClient(socket);
                    socketClient.Completed += connection_Completed;

                    this.Dispatcher.BeginInvoke(new Action(delegate
                    {
                        if (socket != null && socket.RemoteEndPoint != null)
                            //将 通信套接字的 客户端IP端口保存在下拉框里
                            listbox.Items.Add(new TextBlock { Text = socket.RemoteEndPoint.ToString() });

                        ShowMsg("接收一个客户端连接......");
                    }), null);
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message);
                    socketWatch.Close();
                    socketWatch.Dispose();
                    isWatch = false;
                }

            }
        }

        //发送消息到已经连接到 PC 的客户端
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtInput.Text))
            {
                ShowMsg("输入内容不能为空");
                return;
            }

            if (socketClient != null)
            {
                ShowMsg(txtInput.Text.Trim());

                // 发送文字内容
                socketClient.Send(txtInput.Text.Trim());

                txtInput.Text = "";
            }
            else
            {
                MessageBox.Show("还没有建立连接");
            }
        }

        //选择要发送的文件
        private void btnChooseFile_Click(object sender, EventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            if (openFileDialog.ShowDialog() == true)
            {
                txtFilePath.Text = openFileDialog.FileName;
            }
        }

        //发送文件
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFilePath.Text))
            {
                MessageBox.Show("请先选择一个文件");
                return;
            }

            //connection = new SocketClient();

            if (socketClient != null)
            {
                // 发送文件内容
                socketClient.SendFile(txtFilePath.Text.Trim());
            }
            else
            {
                MessageBox.Show("还没有建立连接");
            }
        }

        // 操作完成
        void connection_Completed(object sender, string e)
        {
            ShowMsg(e);
        }

        // 向窗口追加消息
        void ShowMsg(string strMsg)
        {
            this.Dispatcher.BeginInvoke(new Action(delegate
            {
                txtResult.Text += Environment.NewLine + strMsg + Environment.NewLine;
                scroll.ScrollToBottom();
            }), null);
        }

        // 当服务器关闭时触发
        protected override void OnClosed(EventArgs e)
        {
            if (socketWatch != null)
            {
                socketWatch.Close();
                socketWatch.Dispose();
            }
            base.OnClosed(e);
        }

        // 按“回车键”发送消息
        private void txtInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSendMsg_Click(null, null);
            }
        }
    }
}
